package org.pine.oauth2;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.util.internal.NoOpTypeParameterMatcher;
import org.springframework.cglib.proxy.NoOp;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName MyWebSecurityConfig
 * @Description TODO
 * @Author liucs
 * @Date 2021-02-18
 * @Version V1.0
 */
//@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
     PasswordEncoder passwordEncoder(){
        DelegatingPasswordEncoder delegatingPasswordEncoder= (DelegatingPasswordEncoder) PasswordEncoderFactories.createDelegatingPasswordEncoder();
        delegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(NoOpPasswordEncoder.getInstance());
        return delegatingPasswordEncoder;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("1234").roles("ADMIN","USER")
                .and()
                .withUser("pine").password("1234").roles("USER")
                .and()
                .withUser("madder").password("1234").roles("ADMIN","DBA");
    }

    /**
     * 资源安全访问
     * @param http
     * @throws Exception 异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**")
                .hasRole("ADMIN")
                .antMatchers("/users/**")
                .access("hasAnyRole('ADMIN','USER')")
                .antMatchers("/db/**")
                .access("hasRole('ADMIN') and hasRole('DBA')").anyRequest()
                .authenticated().and()
                .formLogin()
                // 设置登录页 login_page
                .loginPage("/login_page")
                // 设置登录请求处理接口
                .loginProcessingUrl("/login")
                // 设置登录认证所需的用户名和密码的参数名
                .usernameParameter("name")
                .passwordParameter("password")
                // 登录成功的业务处理逻辑
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException, ServletException {
                        Object principal=auth.getPrincipal();
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out=resp.getWriter();
                        resp.setStatus(200);
                        Map<String,Object> map=new HashMap<>(10);
                        map.put("status",200);
                        map.put("msg",principal);
                        ObjectMapper om=new ObjectMapper();
                        out.write(om.writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                // 登录失败的业务处理逻辑
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out=resp.getWriter();
                        resp.setStatus(401);
                        Map<String,Object> map=new HashMap<>(10);
                        map.put("status",401);
                        if (e instanceof LockedException){
                            map.put("msg","账户被锁定，登录失败！");
                        }else if(e instanceof BadCredentialsException){
                            map.put("msg","账户名或密码输入错误，登录失败！");
                        }else if (e instanceof DisabledException){
                            map.put("msg","账户被禁用，登录失败！");
                        }else if (e instanceof AccountExpiredException){
                            map.put("msg","账户已过期，登录失败！");
                        }else if (e instanceof CredentialsExpiredException){
                            map.put("msg","密码已过期，登录失败！");
                        }else{
                            map.put("msg","登录失败！");
                        }
                        ObjectMapper om=new ObjectMapper();
                        out.write(om.writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .and()
                // 配置登录注销
                .logout()
                // 设置注销请求URL
                .logoutUrl("/logout")
                // 清除身份认证信息
                .clearAuthentication(true)
                // session 失效
                .invalidateHttpSession(true)
                .addLogoutHandler(new LogoutHandler() {
                    @Override
                    public void logout(HttpServletRequest req, HttpServletResponse resp, Authentication auth) {
                            // 可以处理下额外的工作，比如清除cookie,等常见处理
                        System.out.println("用户已注销！");
                    }
                })
                // 注销成功后的业务逻辑
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException, ServletException {
                        resp.sendRedirect("/login_page");
                    }
        })
                .permitAll()
                .and()
                .csrf().disable();


    }
}
